let env;
let player;
let trainer;
let canvas;


function update() {
    let ctx = canvas.getContext("2d");
    let width = canvas.width;
    let height = canvas.height;
    let cellWidth = width / 3;
    let cellHeight = height / 3;
    let chessWidth = cellWidth * 0.9;
    let chessHeight = cellWidth * 0.9;
    ctx.fillStyle = "Linen"
    ctx.fillRect(0, 0, canvas.width, canvas.height);

    ctx.strokeStyle = "green";
    ctx.beginPath();
    for (let x = 1; x < 3; x++) {
        ctx.moveTo(cellWidth * x, 0);
        ctx.lineTo(cellWidth * x, height);
    }
    for (let y = 1; y < 3; y++) {
        ctx.moveTo(0, cellHeight * y);
        ctx.lineTo(height, cellHeight * y);
    }
    ctx.stroke();

    function cellCenter(x, y) {
        return {x: (x + 0.5) * cellWidth, y: (y + 0.5) * cellHeight};
    }

    ctx.fillStyle = 'black';
    ctx.font = parseInt(Math.min(chessWidth, chessHeight)) + 'px sans';
    ctx.textAlign = 'center';
    ctx.textBaseline = 'middle'
    for (let x = 0; x < 3; x++) {
        for (let y = 0; y < 3; y++) {
            let chess = env.getStateAt(x, y);
            if (chess === null)
                continue;
            let center = cellCenter(x, y);
            ctx.fillText(chess == Role.White ? "○" : "×", center.x, center.y);
        }
    }
}


function showGameResult(role) {
	let result = env.getGameResult(role);
	if (result === 'win')
		alert('得胜！');
	else if (result === 'lose')
		alert('你输了');
	else if (result === 'draw')
		alert('平局')
}


function onCanvasClick(e) {
    let x = event.pageX - canvas.getBoundingClientRect().left;
    let y = event.pageY - canvas.getBoundingClientRect().top;
    let cellWidth = canvas.width / 3;
    let cellHeight = canvas.height / 3;
    let col = parseInt(x / cellWidth);
    let row = parseInt(y / cellHeight);
    let index = row * 3 + col;
    if (env.actionAvailable(index)) {
        let ret = env.play(Role.Black, index);
        if (ret.gameOver) {
			showGameResult(Role.Black);
            return;
        }
        let env2 = new Env();
        trainer.train(player, env2, 500, env.getState(Role.Black), 1.0);
        trainer.train(player, env2, 500, env.getState(Role.Black), 0.2);
        let action = player.getAction(Role.White, env, 0);
        if (action === null) {
            console.log("no available action");
            return;
        }
        ret = env.play(Role.White, action);
        if (ret.gameOver) {
			showGameResult(Role.Black);
            return;
        }
    }
}

function main() {
    env = new Env();
    canvas = document.getElementById("canvas");
    canvas.onclick = onCanvasClick;
    setInterval("update();", 100);

    player = new Player();
    trainer = new MonteCarloTrainer();
    //trainer.train(player, env, 10000, '000000000');
}